<!DOCTYPE html>
<html>
  <head>
    <title></title>
    <style type="text/css">
      #local-video {
        position: absolute;
        top: 120px;
        left: 480px;
        width: 100px;
        z-index: 9999;
        border: 1px solid #ddd;
      }
      #remote-video {
        position: absolute;
        top: 100px;
        left: 100px;
        width: 500px;
      }
    </style>
  </head>
  <body>
    <video id="local-video" autoplay></video>
    <video id="remote-video" autoplay></video>
  </body>
  <script type="text/javascript">
    function hasUserMedia() {
      navigator.getUserMedia = navigator.getUserMedia || navigator.msGetUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia
      return !!navigator.getUserMedia
    }

    function hasRTCPeerConnection() {
      window.RTCPeerConnection =
        window.RTCPeerConnection || window.webkitRTCPeerConnection || window.mozRTCPeerConnection || window.msRTCPeerConnection
      return !!window.RTCPeerConnection
    }
  </script>
  <script>
    const localVideo = document.getElementById("local-video")
    const remoteVideo = document.getElementById("remote-video")
    let yourConnection, theirConnection

    if (hasUserMedia()) {
      navigator.mediaDevices
        .getUserMedia({ video: true, audio: false })
        .then(stream => {
          localVideo.srcObject = stream
          if (hasRTCPeerConnection()) {
            startPeerConnection(stream)
          } else {
            console.log("没有RTCPeerConnection API")
          }
        })
        .catch(error => {
          console.log(error)
        })
    } else {
      alert("没有 userMedia API")
    }
    function startPeerConnection(stream) {
      // 这里使用了几个公共的 stun 协议服务器
      var config = {
        iceServers: [{ url: "stun:stun.services.mozilla.com" }, { url: "stun:stunserver.org" }, { url: "stun:stun.l.google.com:19302" }],
      }
      yourConnection = new RTCPeerConnection(config)
      theirConnection = new RTCPeerConnection(config)

      yourConnection.onicecandidate = function (e) {
        if (e.candidate) {
          theirConnection.addIceCandidate(new RTCIceCandidate(e.candidate))
        }
      }
      theirConnection.onicecandidate = function (e) {
        if (e.candidate) {
          yourConnection.addIceCandidate(new RTCIceCandidate(e.candidate))
        }
      }
    }
  </script>
</html>
